<template>
  <div>
    <el-upload

      :ref="item && item.vModel"
      v-bind="{...item}"
      :accept="(item.accept || []).join(',')"
      :multiple="item.multiple"
      :limit="item.limit"
      :before-upload="beforeUpload"
      :file-list="fileList || []"
      :on-change="handleChange"
      :on-preview="handlePreview"
      :on-remove="uploadRemove"
      :on-exceed="handleExceed"
      :http-request="httpRequest"
    >
    <!-- :action="item.action" -->
    <!-- :on-success="uploadSuccess"
    :http-request="httpRequest" -->
      <i v-if="item.config['list-type'] === 'picture-card'" class="el-icon-plus" />
      <el-button v-else icon="el-icon-upload" size="small" type="primary">
        {{ item.config.buttonText }}
      </el-button>
      <div
        v-if="item.config.showTip"
        slot="tip" class="el-upload__tip"
      >
        只能上传不超过 {{ item.config.fileSize }}{{ item.config.sizeUnit }}的{{ (item.accept || []).join(',') }}文件,最多不超过{{ item.limit }}个文件
      </div>
    </el-upload>
  </div>
</template>

<script>
import uploadMixin from '../uploadMixin'
import mixin from '../mixin'
import _ from "lodash"
import {jsonSimpleClone} from "../../../utils"
import axios from 'axios'

const axiosSourceMap = new Map()
export default {
  name: 'TUpload',
  mixins: [uploadMixin, mixin],
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      uploading: false,
      fileList: [],
      cacheFileData: [],
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.fileList = this.changeValue
  },
  methods: {
    httpRequest(item) {
      const formData = new FormData()
      formData.append('file', item.file)

      this.$store.dispatch('form/uploadStatusMap', {
        [item.file.uid]: 1
      })
      const xhr = new XMLHttpRequest();
      xhr.timeout = 3600000
      xhr.onload = (e) => {
        if (xhr.status !== 200) {
          console.error(`Error ${xhr.status}: ${xhr.statusText}`);
        } else {
          const res = JSON.parse(xhr.responseText)
          console.log(item, res, 'item----sucess')
          const {data} = res
          let oldFileList = this.changeValue
          if (!oldFileList) {
            oldFileList = []
          }
          console.log(data,'data')
          oldFileList.push({name: item.file.name, url: data,uid:item.file.uid})
          this.changeValue = oldFileList
          // this.fileList=this.changeValue
          console.log(this.changeValue,'changeValue')
          item.onSuccess()
          // console.log(); // 输出响应内容
        }

        this.$store.dispatch('form/uploadStatusMap', {
          [item.file.uid]: 2
        })
        axiosSourceMap.delete(item.file)
      }
      xhr.upload.onprogress = (e) => { //监听onprogress事件获取进度
        if (e.lengthComputable) {
          const percentComplete = e.loaded / e.total * 100;
          item.onProgress({status: 'uploading', percent: percentComplete})
        }
      };
      xhr.open('POST', `${item.action}?_=${new Date().getTime()}`);
      xhr.send(formData);
      axiosSourceMap.set(item.file, xhr)
    },
    handleChange(file, files) {
      this.fileList = files
    },
    handleProgress(event, file, fileList) {
      this.uploading = true
    },
    handlePreview(file) {
      console.log(file,'file')
      const elink = document.createElement('a')
      elink.style.display = 'none'
      if (!file.url) {
        file.url = URL.createObjectURL(file.raw);
      }
      elink.href = file.url
      var name = file.name.replace(/<[^>]+>/g, '')
      console.log(name,'eeeeeeeee')
      elink.download=name
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      // window.open(file.url)
    },
    handleExceed() {
      this.msgError('最多只能上传' + this.item.limit + '个文件')
    },
    getUploadStatus() {
      console.log('UploadStatus', cacheFileStatusMap)
      for (const [item, value] of cacheFileStatusMap.entries()) {
        if ([3, 2].includes(value.status)) return value.status
      }
      return 1
    },
    // 删除成功
    uploadRemove(file, fileList) {
      console.log(file,fileList,'file---remove')
      let tempList = jsonSimpleClone(this.changeValue)
      _.remove(tempList, function (item) {
        return item.uid === file.uid
      })
      this.$store.dispatch('form/uploadStatusMap', {
        [file.uid]: 3
      })
      this.changeValue = tempList
      // axiosSourceMap.delete(item.file)
      if (axiosSourceMap.has(file.raw)) {
        axiosSourceMap.get(file.raw).abort()
      }
      console.log(this.changeValue, fileList, 'this.changeValue----remove')
    }
  }
}
</script>

<style scoped>

</style>
